package com.android.dumiaogou.fragment;


import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dumiaogou.R;
import com.android.dumiaogou.activity.GoodsDetailActivity;
import com.android.dumiaogou.adapt.MytimeViewHolder;
import com.android.dumiaogou.model.WinnerObservable;
import com.android.dumiaogou.model.auction.AuctionActivityData;
import com.android.dumiaogou.model.auction.AuctionActivitySendData;
import com.android.dumiaogou.model.auction.AuctionResultData;
import com.android.dumiaogou.model.auction.Auction_DetailRecentlyData;
import com.android.dumiaogou.model.auction.Auction_DetailRecentlySendData;
import com.android.dumiaogou.model.auction.Auction_JoinBackData;
import com.android.dumiaogou.model.auction.Auction_JoinSendData;
import com.android.dumiaogou.model.auction.UpdateAuctionBean;
import com.android.dumiaogou.model.group.DirectBuyData;
import com.android.dumiaogou.model.group.DirectBuyDataCallback;
import com.android.dumiaogou.service.WebSocketService1;
import com.android.dumiaogou.service.WebSocketService3;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.LoginState;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * 全部商品
 */
public class Fragment3 extends Fragment  {


    @BindView(R.id.sort_listview)
    ListView listview;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
//    @BindView(R.id.sort_viewpager)
//    ViewPager viewPager;
    @BindView(R.id.main_top_title)
    TextView mainTopTitle;
    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;
    private FragmentActivity mcontext;
//    private GroupFragmentPagerAdapters pagerAdapter;
    private BaseAdapter adapter1;
    private AdaptList adapter ;
    private View view;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private Auction_DetailRecentlyData recentlyData = new Auction_DetailRecentlyData();
    private Auction_DetailRecentlySendData recentlySendData = new Auction_DetailRecentlySendData();
    private String currentid;
    private Auction_JoinSendData auction_joinSendData = new Auction_JoinSendData();
    private AuctionActivitySendData auctionActivitySendData = new AuctionActivitySendData();
    private AuctionActivityData auctionactivitydata;
    private Auction_JoinBackData auction_joinBackData = new Auction_JoinBackData();
    private AuctionResultData auctionResultData = new AuctionResultData();
    private HashMap<String,MytimeViewHolder> myViewHolderList = new HashMap<>();
    private HashMap<String,Boolean> isStartMap = new HashMap<>();
    private HashMap<String,Boolean> isMostMap = new HashMap<>();
    private HashMap<String,UpdateAuctionBean> updateBean = new HashMap<>();
    private HashMap<String,UpdateAuctionBean> lastperiodBean = new HashMap<>();
    private LinearLayoutManager layoutmanager = new LinearLayoutManager(mcontext);
    private ArrayList<AuctionActivityData.ListBean> listdata = new ArrayList<>();
    private ArrayList<AuctionActivityData.ListBean> temporary_listdata = new ArrayList<>();
    private Gson gson = new Gson();
    private String gsonstring="";
    private WebSocketService1 service;
    private BroadcastReceiver mBroadcastReceiver;

    private String cid="0";
    private int page=1;
    private int mid;
    private String token;
    private int currentcid;
    protected boolean isLoad = false;
    private Message message,message2,message3,message4;
    private boolean isStartThread = false;
    private ArrayList<DirectBuyData.DataBean> cat_list = new ArrayList<>();
    private String notify_title;
    AlertDialog dialog;

    public Fragment3() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_fragment3, container, false);
        mcontext = getActivity();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        ButterKnife.bind(this, view);
        mainTopTitle.setText("全部商品");
        mainTopTitle.setTextColor(Color.parseColor("#ffffff"));
        mainTopBg.setBackgroundColor(Color.parseColor("#FF2741"));
        if(!LoginState.getInstance().getid(mcontext).equals("")&&LoginState.getInstance().getid(mcontext)!=null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
            token = LoginState.getInstance().getUserInfo(mcontext,2);
        }
        initRecycle();
        ReFreshData();
        /**初始化的时候去加载数据**/
        if(!isStartThread) {
            handler1.post(mRunnable);
            isStartThread =true;
        }
        myViewHolderList.clear();
        temporary_listdata.clear();
        broadcastReceive();
        initData();
        GetDataListData();
        isLoad = true;
        return view;
    }
    @Override
    public void onResume()
    {
        super.onResume();
        if(!LoginState.getInstance().getid(mcontext).equals("")&&LoginState.getInstance().getid(mcontext)!=null) {
            mid = Integer.parseInt(LoginState.getInstance().getid(mcontext));
            token = LoginState.getInstance().getUserInfo(mcontext,2);
            // SetDou();

        }
    }

    protected void initData() {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            auctionActivitySendData.setType("get_auctions");
            auctionActivitySendData.setPage(page);
            auctionActivitySendData.setPer_page(100);
            auctionActivitySendData.setCid(Integer.parseInt(cid));
            gsonstring = gson.toJson(auctionActivitySendData);
            service.setCid(cid);
            service.sendMsg(gsonstring);

        } else {


            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }
    private void initRecycle() {
        adapter = new AdaptList(mcontext,null, "0");
      //  adapter.setLoadMoreView(new CustomLoadMoreView());
      //  adapter.setOnLoadMoreListener(this,mRecyclerView);
        mRecyclerView.setLayoutManager(layoutmanager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) view.findViewById(R.id.top), 0);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent = new Intent(mcontext, GoodsDetailActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW, 1);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID,temporary_listdata.get(position).getId());
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_COMMON_ID, "");
                startActivityForResult(intent, 1);
            }
            });
//        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
//                switch (view.getId()) {
//                    case R.id.rightnow_openteam:
//                        if (LoginState.getInstance().isLogin(mcontext)) {
//                            auction_joinSendData.setType("join_auction");
//                            auction_joinSendData.setId(Integer.parseInt(adapter.getData().get(position).getId()));
//                            auction_joinSendData.setMid(mid);
//                            auction_joinSendData.setToken(token);
//                            gsonstring = gson.toJson(auction_joinSendData);
//                            service.sendMsg(gsonstring);
//                        }
//                        else
//                        {
//                            startActivity(new Intent(mcontext, LoginActivity.class));
//                        }
//                        break;
//
//                }
//                return false;
//            }
//        });
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                cid=cat_list.get(i).getId();
                page = 1;
                myViewHolderList.clear();
                temporary_listdata.clear();
                listdata.clear();
                auctionActivitySendData.setType("get_auctions");
                auctionActivitySendData.setPage(page);
                auctionActivitySendData.setPer_page(100);
                auctionActivitySendData.setCid(Integer.parseInt(cid));
                gsonstring = gson.toJson(auctionActivitySendData);
                service.setCid(cid);
                service.sendMsg(gsonstring);
                currentcid = i;
                adapter1.notifyDataSetChanged();
            }
        });
    }
    private void ReFreshData() {
        if (mRefreshLayout != null) {

            mRefreshLayout.setColorSchemeResources(R.color.app_title);
            mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                page = 1;
//                                myViewHolderList.clear();
//                                temporary_listdata.clear();
//                                listdata.clear();
                                auctionActivitySendData.setType("get_auctions");
                                auctionActivitySendData.setPage(page);
                                auctionActivitySendData.setPer_page(100);
                                auctionActivitySendData.setCid(Integer.parseInt(cid));
                                gsonstring = gson.toJson(auctionActivitySendData);
                                service.setCid(cid);
                                service.sendMsg(gsonstring);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                        mRefreshLayout.setRefreshing(false);
                    }
                }
            });
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)
        {
            case 1:
                if(data!=null) {
                    // 获取传递的数据
                    MyLog.e("dddd","ffff");
                    Bundle bundle = data.getExtras();
                    // 获得返回值
                    String id = bundle.getString("auction_id");
                    String period = bundle.getString("auction_period");
                    recentlySendData.setType("join_log");
                    String order_sn = id + "_" + period;
                    recentlySendData.setOrder_sn(order_sn);
                    recentlySendData.setPage(1);
                    recentlySendData.setPer_page(2);
                    gsonstring = gson.toJson(recentlySendData);
                    service.sendMsg(gsonstring);
                }
                break;
        }
    }
    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                myViewHolderList.clear();
                temporary_listdata.clear();
                listdata.clear();
                auctionActivitySendData.setType("get_auctions");
                auctionActivitySendData.setPage(page);
                auctionActivitySendData.setPer_page(100);
                auctionActivitySendData.setCid(Integer.parseInt(cid));
                gsonstring = gson.toJson(auctionActivitySendData);
                service.setCid(cid);
                service.sendMsg(gsonstring);
                break;

        }
    }
//
//    @Override
//    public void onLoadMoreRequested() {
//        page = page + 1;
//        auctionActivitySendData.setType("get_auctions");
//        auctionActivitySendData.setPage(page);
//        auctionActivitySendData.setPer_page(10);
//        auctionActivitySendData.setCid(Integer.parseInt(cid));
//        gsonstring = gson.toJson(auctionActivitySendData);
//        service.setCid(cid);
//        service.sendMsg(gsonstring);
//    }
    //设置广播监听
    private void broadcastReceive()
    {

        service = WebSocketService1.getInstance();
        // service.sendMsg(get_menus);
        mBroadcastReceiver = new BroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //更新竞买返回消息
                if(action.equals(WebSocketService1.ACTION_NOT1)){
                    Intent intents = mcontext.getIntent();
                    auctionResultData = (AuctionResultData)intent.getBundleExtra("bundle").getSerializable("AuctionResult");
                    if(auctionResultData!=null)
                    {
                        DealWithResult();
                    }
                }

                //更新商品列表
                if(action.equals(WebSocketService1.ACTION_AUCTION1))
                {
                    noData.setVisibility(View.GONE);
                    boolean isUpdateUsername =false;
                    auctionactivitydata = (AuctionActivityData) intent.getBundleExtra("bundle2").getSerializable("AuctionGetAuctions");
                    if(auctionactivitydata.getList()!=null&&auctionactivitydata.getList().size()>0) {
                        int midd=0;
//                        if(auctionactivitydata.getList().get(0).getMid()!=null)
//                        {
//                            midd = Integer.parseInt(auctionactivitydata.getList().get(0).getMid());
//                        }
//                        if(midd>0)
//                        {
//                            isUpdateUsername =true;
//                        }
                        myViewHolderList.clear();
                        listdata = new ArrayList<>();
                        if(page==1)
                        {
                            temporary_listdata.clear();
                        }
                        for (int i = 0; i < auctionactivitydata.getList().size(); i++) {
//                            if(isUpdateUsername)
//                            {
////                                   if (auctionactivitydata.getList().get(i).getUsername() != null && !auctionactivitydata.getList().get(i).getUsername().equals(""))
////                                   {
////                                       currentlyUser.put(auctionactivitydata.getList().get(i).getId(), auctionactivitydata.getList().get(i).getUsername());
////                                   }
//                            }
//                            else {

                            AuctionActivityData.ListBean listBean = auctionactivitydata.getList().get(i);
                            long currentTimeMillis = System.currentTimeMillis()/1000 - 2;
                            int time = listBean.getTime();
                            int start = listBean.getStart();
                            long endTime = currentTimeMillis + time;
                            long startTime = currentTimeMillis + start;
                            String price = listBean.getPrice();
                            price = ObjectUtils.decimalFormat(price);
                            temporary_listdata.add(new AuctionActivityData.ListBean(AuctionActivityData.ListBean.THREE, listBean.getId()
                                    , listBean.getPeriod(), listBean.getTitle()
                                    , listBean.getThumb(), price
                                    , time, start
                                    , listBean.getMid(), listBean.getUsername(),startTime,endTime));
                            listdata.add(new AuctionActivityData.ListBean(AuctionActivityData.ListBean.THREE, listBean.getId()
                                    , listBean.getPeriod(), listBean.getTitle()
                                    , listBean.getThumb(), price
                                    , time, start
                                    , listBean.getMid(), listBean.getUsername(),startTime,endTime));
                            //用于存储标识是否有start时间的map
                            if (start != 0)
                            {
                                isStartMap.put(listBean.getId(), true);
                            }
                            else {
                                isStartMap.put(listBean.getId(), false);
                            }
                            //用于存储标识是否是最高价的map
                            if(listBean.getMid()!=null&&!listBean.getMid().equals(""))
                            {
                                if(listBean.getMid().equals(mid+"")) {
                                    isMostMap.put(listBean.getId(), true);
                                }
                                else
                                {
                                    isMostMap.put(listBean.getId(),false);
                                }
                            }
                            else
                            {
                                isMostMap.put(listBean.getId(), false);
                            }
                            //用于存储标识是否更新数据的map
                            updateBean.put(listBean.getId(),new UpdateAuctionBean());
                            lastperiodBean.put(listBean.getId(),new UpdateAuctionBean());
                            // }
                        }
//                        if(isUpdateUsername)
//                        {
//                            //  handler1.post(mRunnable3);
//                        }
//                        else
//                        {

                        AdapterListData();
                        //}
                    }
                    else
                    {
                        if(page==1)
                        {
                            noData.setVisibility(View.VISIBLE);
                        }
                        adapter.loadMoreEnd();
                    }

                }
                //趣买最新出价（判断自己当前出价是否为最高）
                if (action.equals(WebSocketService3.ACTION_JOINLOG)) {
                    recentlyData = (Auction_DetailRecentlyData) intent.getBundleExtra("bundle5").getSerializable("AuctionJoinLog");

                    if(recentlyData.getList()!=null&&recentlyData.getList().size()>0) {
                        if(recentlyData.getList().get(0).getMid().equals(mid+"")) {
                            isMostMap.put(currentid, true);
                            Message message = new Message();
                            message.what = 5;
                            handler1.sendMessage(message);
                        }
                    }
                }
                //更新商品竞买时间，价格，出价人
                if(action.equals(WebSocketService1.ACTION_JOINBACK1))
                {
                    auction_joinBackData = (Auction_JoinBackData)intent.getBundleExtra("bundle3").getSerializable("AuctionJoinBack");
                    String code = auction_joinBackData.getCode();
                    if(code!=null&&!code.equals(""))
                    {
                        if(Integer.parseInt(code)>0)
                        {
                            ObjectUtils.toast(mcontext,auction_joinBackData.getMsg());
                        }
                    }

                    if(temporary_listdata!=null) {
                        long currentTimeMillis = System.currentTimeMillis()/1000 - 1;
                        boolean isupdateusername = false;
                        for (int i = 0; i < temporary_listdata.size(); i++) {
                            AuctionActivityData.ListBean listBean = temporary_listdata.get(i);
                            int id = Integer.parseInt(listBean.getId());
                            if (auction_joinBackData.getId() == id) {
                                if(auction_joinBackData.getUsername()!=null&&auction_joinBackData.getPrice()>0)
                                {
                                    isupdateusername = true;
                                    isMostMap.put(listBean.getId(),false);
                                    UpdateAuctionBean update = new UpdateAuctionBean();
                                    update.setUsername(auction_joinBackData.getUsername());
                                    update.setPrice(auction_joinBackData.getPrice());
                                    updateBean.put(listBean.getId(),update);
                                    int time = auction_joinBackData.getTime();
                                    if(time >0)
                                    {
                                        listBean.setTime(time);
                                        long endTime = currentTimeMillis + time;
                                        listBean.setEndTime(endTime);
                                    }
                                    if(auction_joinBackData.getMid()>0)
                                    {
                                        listBean.setMid(auction_joinBackData.getMid()+"");
                                    }
                                    break;
                                }
                            }
                        }
                        if(isupdateusername)
                        {
                            handler1.post(mRunnable3);
                        }
                    }
                }
//                   if(action.equals(WebSocketService.ACTION_Nav))
//                   {
//                       navData= (Auction_NavData) intent.getBundleExtra("bundle2").getSerializable("AuctionNav");
//                       GetMenus();
//                   }

            }
        };
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(WebSocketService3.ACTION_JOINLOG);
        myIntentFilter.addAction(WebSocketService1.ACTION_NOT1);
        myIntentFilter.addAction(WebSocketService1.ACTION_AUCTION1);
        myIntentFilter.addAction(WebSocketService1.ACTION_JOINBACK1);

        // myIntentFilter.addAction(WebSocketService.ACTION_Nav);
        //注册广播
        mcontext.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
    /**
     * 处理竞买返回通知消息
     */
    private void DealWithResult()
    {
        /**
         * 趣买返回通知重开
         */
        if(auctionResultData.getTime()>0&&auctionResultData.getStart()>0)
        {
            /**
             * 更新重开的商品时间
             */
            if (temporary_listdata != null) {
                long currentTimeMillis = System.currentTimeMillis()/1000 - 1;
                for (int i = 0; i < temporary_listdata.size(); i++) {
                    AuctionActivityData.ListBean listBean = temporary_listdata.get(i);
                    String id = listBean.getId();
                    if (auctionResultData.getId().equals(id)) {
                        int time = auctionResultData.getTime();
                        listBean.setTime(time);
                        int start = auctionResultData.getStart();
                        listBean.setStart(start);
                        long endTime = currentTimeMillis + time;
                        long startTime = currentTimeMillis + start;
                        listBean.setEndTime(endTime);
                        listBean.setStartTime(startTime);
                        if(auctionResultData.getStart()>0) {
                            isStartMap.put(listBean.getId(), true);
                        }
                        isMostMap.put(listBean.getId(), false);
                        break;
                    }
                }
            }
            /**
             * 有人中拍时
             */
            if(auctionResultData.getMid()>0)
            {
                /**
                 * 更新上期中拍商品活动状态和数据
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setUsername(auctionResultData.getUsername());
                update.setIspass_in(false);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);

                int dataMid = auctionResultData.getMid();
                if (dataMid > 0 && dataMid == mid) {
                    String notify_title = auctionResultData.getTitle();
                    WinnerObservable winnerObservable = WinnerObservable.getInstance();
                    winnerObservable.setNotify_title(notify_title);
                }
            }
            /**
             * 无人中拍时
             */
            else
            {
                /**
                 * 更新上期流拍商品活动状态
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setIspass_in(true);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
        }
        /**
         * 竞买返回通知不重开
         */
        else
        {
            /**
             *
             */
//           if(auction_style.equals("mine_auctioning")) {
//               if (listdata != null) {
//                   for (int i = 0; i < listdata.size(); i++) {
//                       int id = Integer.parseInt(listdata.get(i).getId());
//                       if (auctionResultData.getId() == id) {
//                           listdata.remove(i);
//                           break;
//                       }
//                   }
//               }
//               if (myViewHolderList.containsKey(auctionResultData.getId())) {
//                   myViewHolderList.remove(auctionResultData.getId());
//               }
//           }
            /**
             * 有人中拍时
             */
            if(auctionResultData.getMid()>0)
            {
                /**
                 * 头条
                 */
                String keyName = getString(R.string.app_keyname);
                String content = "恭喜" +auctionResultData.getUsername()+"以"
                        +"<font color='#FF0000'>"+"¥"+auctionResultData.getLast_price()+"</font>"+ keyName + "到"
                        +"<font color='#99ccff'>"+auctionResultData.getTitle()+"</font>";
                /**
                 * 更新上期中拍商品活动状态和数据
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setUsername(auctionResultData.getUsername());
                update.setIspass_in(false);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
            /**
             * 无人中拍时
             */
            else
            {
                /**
                 * 更新上期流拍商品活动状态
                 */
                UpdateAuctionBean update = new UpdateAuctionBean();
                update.setIspass_in(true);
                lastperiodBean.put(auctionResultData.getId()+"",update);
                handler1.post(mRunnable4);
            }
        }
    }

    /**
     * 适配商品列表
     */
    private void AdapterListData()
    {
        mRefreshLayout.setRefreshing(false);
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
        if (page == 1) {
            adapter.setNewData(listdata);

            if (auctionactivitydata.getList().size() < 10 ) {
                adapter.loadMoreComplete();
                adapter.loadMoreEnd();
            }
        } else {
            adapter.addData(listdata);
            adapter.loadMoreComplete();
        }
       // mRecyclerView.setAdapter(adapter);
    }
    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    adapter.notifyTimeData();
                    break;
                case 2:
                    adapter.notifyDataSetChanged();
                    break;
                case 3:
                    adapter.notifyUsernameData();
                    break;
                case 4:
                    adapter.notifyLastPeriod();
                    break;
                case 5:
                    adapter.notifyMostPrice();
                    break;
            }
        }
    };
    //更新上一期活动是否流拍
    private Runnable mRunnable4 = new Runnable() {
        @Override
        public void run() {
            if (null == message4) {
                message4 = new Message();
            } else {
                message4 = Message.obtain();
            }
            message4.what = 4;
            //发送信息给handler
            handler1.sendMessage(message4);
        }
    };
    //更新当前出价和竞拍人
    private Runnable mRunnable3 = new Runnable() {
        @Override
        public void run() {
            if (null == message3) {
                message3 = new Message();
            } else {
                message3 = Message.obtain();
            }
            message3.what = 3;
            //发送信息给handler
            handler1.sendMessage(message3);
        }
    };
    //更新商品是否过期
    private Runnable mRunnable2 = new Runnable() {
        @Override
        public void run() {
            if (null == message2) {
                message2 = new Message();
            } else {
                message2 = Message.obtain();
            }
            message2.what = 2;
            //发送信息给handler
            handler1.sendMessage(message2);
        }
    };
    //更新商品时间
    private Runnable mRunnable = new Runnable(){

        @Override
        public void run() {
            if( temporary_listdata!=null) {
                long currentTimeMillis = System.currentTimeMillis()/1000;
                for (int i = 0; i <  temporary_listdata.size(); i++) {
                    int start;
                    int time;
                    AuctionActivityData.ListBean listBean = temporary_listdata.get(i);
                    long intervalStart = listBean.getStartTime() - currentTimeMillis;
                    if (intervalStart > 0) {
                        start = (int) intervalStart;
                    }else {
                        start = 0;
                    }
                    listBean.setStart(start);
                    long intervalEnd = listBean.getEndTime() - currentTimeMillis;
                    if (intervalEnd > 0) {
                        time = (int) intervalEnd;
                    }else {
                        time = 0;
                    }
                    listBean.setTime(time);
//                    int time =  temporary_listdata.get(i).getTime();
//                    int start =  temporary_listdata.get(i).getStart();
//                    if (start > 0) {
//                        start = start - 1;
//                        temporary_listdata.get(i).setStart(start);
//                    }
//                    if (time > 0) {
//                        time = time - 1;
//                        temporary_listdata.get(i).setTime(time);
//                    }
                }
            }
            if (null == message) {
                message = new Message();
            } else {
                message = Message.obtain();
            }
            message.what = 1;
            //发送信息给handler
            handler1.sendMessage(message);
            //每1000豪秒重启一下线程
            handler1.postDelayed(mRunnable, 1000);
        }
    };

    private void GetDataListData()
    {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_GOODSCATEGORYDATA ;
        if (networkConnected) {

            HttpUtils.get(address,null, new DirectBuyDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(DirectBuyData response, int id) {

                    if (response.getCode() == 0) {

                        if (response.getData() != null) {
                            if ( response.getData()!=null){
                            cat_list.clear();
                            cat_list.add(new DirectBuyData.DataBean("0","全部商品","","","","",""));
                            cat_list.addAll(response.getData());
                                adapter1 = new BaseAdapter() {
                                    @Override
                                    public int getCount() {
                                        return cat_list.size();
                                    }

                                    @Override
                                    public Object getItem(int i) {
                                        return cat_list.get(i);
                                    }

                                    @Override
                                    public long getItemId(int i) {
                                        return i;
                                    }

                                    @Override
                                    public View getView(int i, View view, ViewGroup viewGroup) {
                                        if(view==null) {
                                            view = inflater.inflate(R.layout.item_fragment3_listview, null);
                                        }
                                        LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll);
                                        View v = (View)view.findViewById(R.id.view);
                                        TextView tv_name= (TextView) view.findViewById(R.id.tv);
                                        tv_name.setText(cat_list.get(i).getCatname());
                                        if(currentcid==i)
                                        {
                                            v.setVisibility(View.VISIBLE);
                                            tv_name.setTextColor(getResources().getColor(R.color.app_title));
                                            ll.setBackgroundResource(R.drawable.corner_white_bg);
                                        }
                                       else
                                        {
                                            tv_name.setTextColor(getResources().getColor(R.color.black));
                                            v.setVisibility(View.GONE);
                                            ll.setBackgroundResource(R.drawable.corner_gray_bg2);
                                        }
                                        return view;
                                    }
                                };
                                listview.setAdapter(adapter1);
                            }
                        }
                    }else {

                    }
                }
            });

        } else{

            ObjectUtils.toast(mcontext, "网络未连接");
        }
    }
    public class AdaptList extends BaseMultiItemQuickAdapter<AuctionActivityData.ListBean,MytimeViewHolder> {
        private String type;
        private FragmentActivity mcontext;
        private int limitposition;
        public ArrayList<AuctionActivityData.ListBean> data = new ArrayList();

        public AdaptList(FragmentActivity context, ArrayList<AuctionActivityData.ListBean> data, String type) {
            super(data);
            this.data = data;
            this.mcontext = context;
            this.type = type;
            addItemType(AuctionActivityData.ListBean.THREE, R.layout.item_ry_fragment3);
        }


        @Override
        protected void convert(MytimeViewHolder holder, AuctionActivityData.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case AuctionActivityData.ListBean.THREE:
                    if (!(myViewHolderList.containsKey(mainlistdata.getId()))) {
                        myViewHolderList.put(mainlistdata.getId(), holder);
                        holder.setTime_position(holder.getLayoutPosition());
                    }
                        //判断list里面是否含有该holder，没有就增加
                        //因为list已经持有holder的引用，所有数据自动会改变
//                        int time1 = mainlistdata.getStart();
//                        setCountDown(holder, time1);
                        ObjectUtils.photo2(mcontext, mainlistdata.getThumb(), ((ImageView) holder.getItem_grid_aishang_img()));
                        // holder.setText(R.id.rightnow_phone, mainlistdata.getUsername());
                        holder.getItem_rightnow_price().setText("￥" + mainlistdata.getPrice());
                        holder.getItem_grid_detail_like_title().setText(mainlistdata.getTitle());

//                    if( temporary_listdata!=null) {
//
//                        for (int i = 0; i <  temporary_listdata.size(); i++) {
//                            int time =  temporary_listdata.get(i).getTime();
//                            int start =  temporary_listdata.get(i).getStart();
//
//
//                            if (myViewHolderList.containsKey( temporary_listdata.get(i).getId())) {
//                                boolean isstart = isStartMap.get( temporary_listdata.get(i).getId());
//                                boolean isMost =  isMostMap.get(temporary_listdata.get(i).getId());
//
//                                //有start时间时
//                                if(isstart) {
//                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setText("即将开始");
//                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(false);
//                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_yellow_bg2);
//                                    String minute = String.format("%02d", start/ 3600);
//                                    String second = String.format("%02d", start  % 3600 / 60);
//                                    String millsecond = String.format("%02d", start % 60);
//                                    myViewHolderList.get( temporary_listdata.get(i).getId()).getKill_millsecond().setText(millsecond);
//                                    myViewHolderList.get( temporary_listdata.get(i).getId()).getKill_minute().setText(minute);
//                                    myViewHolderList.get( temporary_listdata.get(i).getId()).getKill_second().setText(second);
//                                    if(start==0)
//                                    {
//                                        myViewHolderList.get( temporary_listdata.get(i).getId()).getRightnow_openteam().setText("立即拼购");
//                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg2);
//                                        myViewHolderList.get( temporary_listdata.get(i).getId()).getItem_rightnow_default().setVisibility(View.VISIBLE);
//                                        myViewHolderList.get( temporary_listdata.get(i).getId()).getItem_lastperiod_failed().setVisibility(View.GONE);
//                                        myViewHolderList.get( temporary_listdata.get(i).getId()).getItem_lastperiod_ll().setVisibility(View.GONE);
//                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
//                                        isStartMap.put( temporary_listdata.get(i).getId(),false);
//                                    }
//                                }
//                                //没有start时间时
//                                else {
//
//                                    String minute = String.format("%02d", time / 3600);
//                                    String second = String.format("%02d", time % 3600 / 60);
//                                    String millsecond = String.format("%02d", time % 60);
//                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getKill_millsecond().setText(millsecond);
//                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getKill_minute().setText(minute);
//                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getKill_second().setText(second);
//                                    if(time>0) {
//                                        if (!isMost) {
//                                            myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setText("立即拼购");
//                                            myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg2);
//                                            myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
//
//                                        } else {
//                                            myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setText("你已最高");
//                                            myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_gray_bg2);
//                                            myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(false);
//                                        }
//                                    }
//                                    if (time == 0) {
//                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setText("出价结束");
//                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_gray_bg2);
//                                    }
//                                }
//                            }
                      // }
                  //  }
                    break;
            }
        }
            //更新当前出价竞拍人
            public void notifyUsernameData() {
                if( temporary_listdata!=null) {

                    for (int i = 0; i <  temporary_listdata.size(); i++) {
                        String id =  temporary_listdata.get(i).getId();
                        if (myViewHolderList.containsKey(id)) {
                            if(updateBean.get(id).getPrice()>0) {
                                isMostMap.put(id,false);
                                myViewHolderList.get(id).getItem_lastperiod_failed().setVisibility(View.GONE);
                                myViewHolderList.get(id).getItem_rightnow_default().setVisibility(View.GONE);
                                myViewHolderList.get(id).getItem_lastperiod_ll().setVisibility(View.VISIBLE);
                                myViewHolderList.get(id).getItem_lastperiod_person().setText("ID: "+updateBean.get(id).getUsername());
                                myViewHolderList.get(id).getItem_rightnow_price().setText("￥" + updateBean.get(id).getPrice());
                                myViewHolderList.get( temporary_listdata.get(i).getId()).getRightnow_openteam().setText(R.string.app_fragment3_keyname);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg2);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
                            }
                        }
                    }
                }
            }
            //更新商品活动最高价
            public void notifyMostPrice() {
                if(temporary_listdata!=null) {
                    for (int i = 0; i <  temporary_listdata.size(); i++) {
                        Auction_DetailRecentlyData data = recentlyData;
                        String id = temporary_listdata.get(i).getId();
                        if (myViewHolderList.containsKey(id)&&temporary_listdata.get(i).getMid()!=null&&!temporary_listdata.get(i).getMid().equals("")) {

                            if(temporary_listdata.get(i).getMid().equals(data.getList().get(0).getMid())) {
                                isMostMap.put(id, true);
                                myViewHolderList.get(id).getItem_lastperiod_failed().setVisibility(View.GONE);
                                myViewHolderList.get(id).getItem_rightnow_default().setVisibility(View.GONE);
                                myViewHolderList.get(id).getItem_lastperiod_ll().setVisibility(View.VISIBLE);
                                myViewHolderList.get(id).getItem_lastperiod_person().setText("ID: "+data.getList().get(0).getUsername());
                                myViewHolderList.get(id).getItem_rightnow_price().setText("￥"+ data.getList().get(0).getPrice());
                                myViewHolderList.get(id).getRightnow_openteam().setText("你已最高");
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_gray_bg2);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(false);
                            }
                        }
                    }
                }
            }
            //更新上期商品活动是否失效
            public void notifyLastPeriod() {
                if(temporary_listdata!=null) {
                    for (int i = 0; i <  temporary_listdata.size(); i++) {
                        String id = temporary_listdata.get(i).getId();
                        if(auctionResultData.getId().equals(id)) {
                            if (myViewHolderList.containsKey(id)) {
                                myViewHolderList.get(id).getItem_rightnow_price().setText("￥0");
                                myViewHolderList.get( temporary_listdata.get(i).getId()).getRightnow_openteam().setText(R.string.app_fragment3_keyname);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg2);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
                                if (lastperiodBean.get(id).ispass_in()) {
                                    myViewHolderList.get(id).getItem_rightnow_default().setVisibility(View.GONE);
                                    myViewHolderList.get(id).getItem_lastperiod_failed().setVisibility(View.VISIBLE);
                                    myViewHolderList.get(id).getItem_lastperiod_ll().setVisibility(View.GONE);
                                } else {
                                    myViewHolderList.get(id).getItem_lastperiod_failed().setVisibility(View.GONE);
                                    myViewHolderList.get(id).getItem_rightnow_default().setVisibility(View.GONE);
                                    myViewHolderList.get(id).getItem_lastperiod_ll().setVisibility(View.VISIBLE);
                                    String lastDes = getString(R.string.app_last_winner);
                                    myViewHolderList.get(id).getItem_lastperiod_person().setText(lastDes + lastperiodBean.get(id).getUsername());
                                }
                            }
                        }
                    }
                }
            }
            //更新全部商品时间
            public void notifyTimeData(){

                if( temporary_listdata!=null) {

                    for (int i = 0; i <  temporary_listdata.size(); i++) {

                        int time =  temporary_listdata.get(i).getTime();
                        int start =  temporary_listdata.get(i).getStart();

                        if (myViewHolderList.containsKey( temporary_listdata.get(i).getId())) {

                            boolean isstart = isStartMap.get( temporary_listdata.get(i).getId());
                            boolean  isMost=  isMostMap.get(temporary_listdata.get(i).getId());


                            //有start时间时
                            if(isstart) {
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setText("即将开始");
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(false);
                                myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_yellow_bg2);
                                setCountDown(myViewHolderList.get( temporary_listdata.get(i).getId()), start);
                                if(start==0)
                                {
                                    myViewHolderList.get( temporary_listdata.get(i).getId()).getRightnow_openteam().setText(R.string.app_fragment3_keyname);
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg2);
                                    myViewHolderList.get( temporary_listdata.get(i).getId()).getItem_rightnow_default().setVisibility(View.VISIBLE);
                                    myViewHolderList.get( temporary_listdata.get(i).getId()).getItem_lastperiod_failed().setVisibility(View.GONE);
                                    myViewHolderList.get( temporary_listdata.get(i).getId()).getItem_lastperiod_ll().setVisibility(View.GONE);
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);
                                    isStartMap.put( temporary_listdata.get(i).getId(),false);
                                }
                            }
                            //没有start时间时
                            else {

                                setCountDown(myViewHolderList.get(temporary_listdata.get(i).getId()), time);
                                if(time>0) {
                                    if (!isMost) {
                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setText(R.string.app_fragment3_keyname);
                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_red_bg2);
                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(true);

                                    } else {
                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setText("你已最高");
                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_gray_bg2);
                                        myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(false);
                                    }
                                }
                                if (time == 0) {
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getKill_millsecond().setText("00");
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getKill_minute().setText("00");
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getKill_second().setText("00");
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setText("出价结束");
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setBackgroundResource(R.drawable.corner_gray_bg2);
                                    myViewHolderList.get(temporary_listdata.get(i).getId()).getRightnow_openteam().setEnabled(false);
                                    isMostMap.put( temporary_listdata.get(i).getId(),false);
                                }
                            }
                        }
                    }
                }
            }
    }

    private void setCountDown(MytimeViewHolder holder, int time) {
        int day = 60 * 60 * 24;
        int hour = 60 * 60;
        int min = 60;
        double d1 = time * 1.0 / day;
        if(time < 0){
            time = 0;
        }
        if(d1 > 1){
            holder.getLl_count_down1().setVisibility(View.GONE);
            holder.getLl_count_down2().setVisibility(View.VISIBLE);
            int dayNum = time / day;
            int hourNum = time /hour % 24;
            int minuteNum = time /min % 60;
            holder.getCd_day().setText(dayNum+"天");
            holder.getCd_hour().setText(hourNum+"时");
            holder.getCd_minute().setText(minuteNum+"分");
        }else {
            holder.getLl_count_down1().setVisibility(View.VISIBLE);
            holder.getLl_count_down2().setVisibility(View.GONE);
            String hour1 = String.format("%02d", time / 3600);
            String minute1 = String.format("%02d", time % 3600 / 60);
            String second1 = String.format("%02d", time % 60);
            holder.getKill_minute().setText(hour1);
            holder.getKill_second().setText(minute1);
            holder.getKill_millsecond().setText(second1);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        listdata.clear();
        temporary_listdata.clear();
        myViewHolderList.clear();
        service = null;
        handler1.removeCallbacks(mRunnable);
        getActivity().unregisterReceiver(mBroadcastReceiver);
        mBroadcastReceiver  = null;
    }

}
